

import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.facebook.api.FacebookException;
import com.facebook.api.FacebookRestClient;
import com.facebook.api.ProfileField;
import com.facebook.api.TemplatizedAction;
import com.facebook.api.schema.User;
import com.facebook.api.schema.UsersGetInfoResponse;

import edu.uci.ics.jung.graph.decorators.StringLabeller.UniqueLabelException;

/**
 * Servlet implementation class for Servlet: FBUser
 *
 */
public class FBManagement extends FacebookServlet implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;

	public FacebookRestClient fbrclient;
	public Database db;

//	Recuperation des informations du logué :
//	private ArrayList <String> noms_mes_amis = null ;

//	Liste des id des amis de l'utilisateur logué :
//	private ArrayList <Long> id_mes_amis = null ;

//	Liste des amis par ID : (En clef -> l'ID de la personne, en valeur -> la liste des ID de ses amis)
	public HashMap<Long, ArrayList <Long>> tab_id_friends = null ;
	public HashMap<Long, String> tab_noms = null ;
	public HashMap<Long, String> tab_pic = null ;

//	Relation entre les gens : (ArrayList<Long> est de taille 2 (couple relation))
	public HashSet<ArrayList<Long>> relations_amis = null ;

//	ID de l'utilisateur logué : 
	public long myID;

//	Nom de l'utilisateur logué : 
//	private ArrayList<String> tab_Pic_Square;

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public FBManagement() {
		super();

		db = new Database("com.mysql.jdbc.Driver");
		db.open("jdbc:mysql://mysql.alwaysdata.com/gestionprojet_facebook","gestionprojet", "polytech");

		tab_id_friends = new HashMap<Long, ArrayList<Long>>() ;
		tab_noms = new HashMap<Long, String>() ;
		tab_pic = new HashMap<Long, String>() ;
		relations_amis = new HashSet<ArrayList<Long>>() ;
	}   	

	public void creerGraphe() throws UniqueLabelException
	{
		/*
		System.out.println("Noms_amis :");
		System.out.println(noms_mes_amis);
		System.out.println("Fin Noms_amis :");

		System.out.println("relations_amis :");
		System.out.println(relations_amis);
		System.out.println("Fin relations_amis :");

		System.out.println("tab_Pic_Square :");
		System.out.println(tab_Pic_Square);
		System.out.println("Fin tab_Pic_Square :");
		 */

//		VertexImageShaper vis = new VertexImageShaper(db, fbrclient, id_mes_amis, noms_mes_amis, relations_amis, tab_Pic_Square, tab_friends_by_id) ;
		VertexImageShaper vis = new VertexImageShaper(this) ;
		System.out.println("Graphe cree");

	}

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Servlet : FBM!!");
		fbrclient = getAuthenticatedFacebookClient(request, response);
		if(fbrclient == null)
			return;

//		if (fbrclient == null){
//		request.getRequestDispatcher("LoginGraphes").forward(request, response);
//		return;
//		}

		try {
			myID = fbrclient.users_getLoggedInUser();
		} catch (FacebookException e) {
			e.printStackTrace();
		}

		System.out.println("1");
//		Recuperation des informations du logué :
		getUserInfos(myID);



		System.out.println("2");
//		Creer le code du graphe :
		try {
			creerGraphe();
		} catch (UniqueLabelException e) {
			e.printStackTrace();
		}

		System.out.println("3");

		request.getRequestDispatcher("graphe.jsp").forward(request, response);
		System.out.println("Fin DoGet");
	}  	

	//Va chercher tous les noms utiles pour tracer le graphe
	public void  getUserInfos(Long id_user) {
		try {
			EnumSet<ProfileField> fields = EnumSet.of(
					com.facebook.api.ProfileField.PIC_SQUARE,
					com.facebook.api.ProfileField.NAME);

//			Contient les ID des amis (en 0, c'est l'ID de l'utilisateur courant)
			ArrayList<Long> id_my_friends = new ArrayList<Long>();
			id_my_friends.add(id_user);


//			On récupère ses copains : 
			String requete = "Select idf1,idf2 From friends Where idf1 = " + id_user + " OR idf2 = " + id_user;
			DataSet ds = db.executeQuery(requete);
			String[] res;

			while(ds.hasMoreElements()){
				res = ds.nextElement();
				if (Integer.parseInt(res[1]) == id_user){
					id_my_friends.add(Long.parseLong(res[2]));

				}
				else{
					id_my_friends.add(Long.parseLong(res[1]));

				}
			}
			tab_id_friends.put(id_user, id_my_friends);


			System.out.println("a");
//			ArrayList du milieu est de taille 2 :  
			add_friends_of_friends(id_user);
			System.out.println("b");
			make_relations(id_user) ;
			System.out.println("c");

//			Recuperation des informations :
			fbrclient.users_getInfo(id_my_friends, fields);
			UsersGetInfoResponse usersInfo = (UsersGetInfoResponse) fbrclient
			.getResponsePOJO();

			List<User> userList = usersInfo.getUser();

			for (User u : userList){
				tab_noms.put(u.getUid(), u.getName());
				tab_pic.put(u.getUid(), u.getPicSquare()) ;
			}


		} catch (FacebookException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}


	}

//	Méthode d'ajout d'amis à partir de tous les amis d'id_user : 
//	TODO : incomplet 
	public void add_friends_of_friends(Long id_user) {
		ArrayList<Long> id_mes_amis = tab_id_friends.get(id_user);
		for (int i = 1; i < id_mes_amis.size(); ++i){
			if ( ! tab_id_friends.containsKey(id_mes_amis.get(i)) )
			{
				ArrayList<Long> liste_id_amis_courant = new ArrayList<Long>() ;

				String requete = "Select idf1,idf2 From friends Where idf1 = " + id_mes_amis.get(i) + " OR idf2 = " + id_mes_amis.get(i);
				DataSet ds = db.executeQuery(requete);
				String[] res;

				while(ds.hasMoreElements()){
					res = ds.nextElement();
					if (Long.parseLong(res[1]) == id_mes_amis.get(i)){
						liste_id_amis_courant.add(Long.parseLong(res[2]));
					}
					else{
						liste_id_amis_courant.add(Long.parseLong(res[1]));
					}
				}

				tab_id_friends.put(id_mes_amis.get(i), liste_id_amis_courant);
			}
		}
	}

//	Détermine les relations entre les amis : 
	public void make_relations(Long id_user) {
		ArrayList<Long> id_mes_amis = tab_id_friends.get(id_user) ;
		for (int i = 1; i < id_mes_amis.size(); ++i){
			ArrayList<Long> amis_id_courant = tab_id_friends.get(id_mes_amis.get(i)) ;
			for (int j = i+1 ; j < id_mes_amis.size(); ++j){
				if ( amis_id_courant.contains(id_mes_amis.get(j)))
				{
					if ( id_mes_amis.get(i) < id_mes_amis.get(j))
					{
						ArrayList<Long> new_relation = new ArrayList<Long>();
						new_relation.add(id_mes_amis.get(i)) ;
						new_relation.add(id_mes_amis.get(j)) ;
						relations_amis.add(new_relation) ;
					}
					else 
					{
						ArrayList<Long> new_relation = new ArrayList<Long>();
						new_relation.add(id_mes_amis.get(j)) ;
						new_relation.add(id_mes_amis.get(i)) ;
						relations_amis.add(new_relation) ;
					}
				}
			}
		}
	}


	public void envoyerBaffes(Long uids){

		String struids = "";
		ArrayList<Long> luids = new ArrayList<Long>();
		luids.add(uids);

		System.out.println(uids);

		envoyerSQLBaffe(myID,uids);


		TemplatizedAction action = new TemplatizedAction("{actor} a mis une baffe à {target}");                      //the user has recommended a book
		action.addTargetIds(struids);
		action.setBodyTemplate("{actor} utilise Fous Des Baffes!");                                               //set a body template (optional)
		action.setBodyGeneral("Toi aussi tu veux mettre des claques a tes amis? <br/> <a href='http://apps.facebook.com/fousdesbaffes'>Fous Des Baffes</a>");                                     //set general body content (optional)
		action.addPicture("http://www.la-compagnie-des-elfes.com/catalog/images/main%20perfo.jpg", "http://apps.facebook.com/fousdesbaffes");    //add up to 4 pictures (optional)

		try {
			//publier feed
			fbrclient.feed_PublishTemplatizedAction(action); //publish to feed

			//envoyer notification
			fbrclient.notifications_send(luids, "viens de te mettre une baffe");
			System.out.println("Myid="+myID );
			fbrclient.notifications_sendFbmlEmail(luids, "Tu t'es pris une baffe", "<fb:name uid="+myID+" /> viens de te mettre une baffe");

		} catch (FacebookException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void envoyerSQLBaffe(long idE, long idR){
		String requete = "INSERT into baffes VALUES(NULL, " + idE + ", " + idR + ", now())";
		db.executeUpdate(requete);
	}


	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}   	  	  

	/* (non-Javadoc)
	 * @see javax.servlet.GenericServlet#init()
	 */
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}   
}